package com.chexiehui.jc.ui.activity;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
import com.aries.ui.view.radius.RadiusEditText;
import com.aries.ui.view.radius.RadiusTextView;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.R;
import com.chexiehui.jc.adapter.CommVLayoutAdapter;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpActivity;
import com.chexiehui.jc.base.BasePage;
import com.chexiehui.jc.entity.PostCommentInfo;
import com.chexiehui.jc.event.PostCommentChildAppraiseChangeEvent;
import com.chexiehui.jc.event.PostCommentChildLikeChangeEvent;
import com.chexiehui.jc.event.SoftKeyboardShowOrHideEvent;
import com.chexiehui.jc.mvp.forum.ForumAppraiseDetailsCovenant;
import com.chexiehui.jc.mvp.forum.ForumAppraiseDetailsPresenter;
import com.chexiehui.jc.utils.AppCommonUtil;
import com.chexiehui.jc.utils.GlideUtil;
import com.chexiehui.jc.utils.NoDoubleClickListener;
import com.chexiehui.jc.utils.SoftKeyboardFixerForFullscreen;
import com.chexiehui.jc.widget.AppBar2Behavior;
import com.chexiehui.jc.widget.AppBarBehavior;
import com.chexiehui.jc.widget.CircleImageView;
import com.chexiehui.jc.widget.LoadingLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

public class ForumAppraiseDetailsActivity extends BaseMvpActivity<ForumAppraiseDetailsPresenter> implements ForumAppraiseDetailsCovenant.View {

    @BindView(R.id.iv_person_avatar)
    CircleImageView ivPersonAvatar;
    @BindView(R.id.tv_person_name)
    TextView tvPersonName;
    @BindView(R.id.tv_person_car_brand)
    TextView tvPersonCarBrand;
    @BindView(R.id.rtv_person_zan_count)
    TextView rtvPersonZanCount;
    @BindView(R.id.tv_comment_content)
    TextView tvCommentContent;
    @BindView(R.id.tv_comment_time)
    TextView tvCommentTime;
    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.ret_input_content)
    RadiusEditText retInputContent;
    @BindView(R.id.ll_bottom_input_panel)
    LinearLayout llBottomInputPanel;
    @BindView(R.id.rtv_text_content)
    RadiusTextView rtvTextContent;
    @BindView(R.id.ll_bottom_info_panel)
    LinearLayout llBottomInfoPanel;
    @BindView(R.id.abl_container)
    AppBarLayout ablContainer;
    private DelegateAdapter listAdapter;
    private CommVLayoutAdapter<PostCommentInfo> appraiseAdapter;
    private BasePage<PostCommentInfo> page;
    private PostCommentInfo commentInfo;
    private String postId = "";
    private String commentId = "";
    @BindView(R.id.loadingLayout)
    LoadingLayout loadingLayout;

    @Override
    protected void beforeSetView() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            postId = bundle.getString("postId");
            commentId = bundle.getString("commentId");
        }
        if(postId == null) postId = "";
        if(commentId == null) commentId = "";
    }

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void setTitleBar() {
        titleBar.setTitleMainText("详情");
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_forum_appraise_details;
    }

    @Override
    protected void initView(Bundle var1) {
        SoftKeyboardFixerForFullscreen.assistActivity(this);
        loadingLayout.setOnReloadListener(v -> {
            if (StringUtils.isTrimEmpty(postId)) {
                loadingLayout.setStatus(LoadingLayout.Empty);
                loadingLayout.setEmptyText("没有找到任何数据");
                return;
            }
            mvpPresenter.getCommentInfo();
        });
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setEnableOverScrollDrag(false);
        refreshLayout.setDisableContentWhenLoading(true);
        refreshLayout.setDisableContentWhenRefresh(true);
        refreshLayout.setEnableFooterFollowWhenLoadFinished(false);
        refreshLayout.setEnableLoadMoreWhenContentNotFull(false);
        refreshLayout.setEnableScrollContentWhenRefreshed(true);
        refreshLayout.setEnableOverScrollDrag(true);
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mvpPresenter.getCommentInfo();
            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (page != null && page.getTotalRecordCount() > appraiseAdapter.getData().size()) {
                    mvpPresenter.getCommentList(page.getPageIndex() + 1);
                } else {
                    refreshLayout.finishLoadMoreWithNoMoreData();
                }
            }
        });
        retInputContent.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEND) {
                if (!StringUtils.isTrimEmpty(retInputContent.getText().toString().trim())) {
                    PostCommentInfo tag = (PostCommentInfo) retInputContent.getTag();
                    KeyboardUtils.hideSoftInput(retInputContent);
                    if(tag == null){
                        mvpPresenter.addComment(retInputContent.getText().toString().trim());
                    }else{
                        mvpPresenter.addReply(retInputContent.getText().toString().trim(), tag.getAuthorId(), tag.getAuthorName(), tag.getContent());
                    }
                }
                return true;
            }
            return false;
        });
        VirtualLayoutManager virtualLayoutManager = new VirtualLayoutManager(mContext);
        recycler.setLayoutManager(virtualLayoutManager);
        ((SimpleItemAnimator) recycler.getItemAnimator()).setSupportsChangeAnimations(false);
        final RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        recycler.setRecycledViewPool(viewPool);
        viewPool.setMaxRecycledViews(0, 20);
        listAdapter = new DelegateAdapter(virtualLayoutManager, false);
        recycler.setAdapter(listAdapter);

        CoordinatorLayout.LayoutParams params = new CoordinatorLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.setBehavior(new AppBar2Behavior());
        ablContainer.setLayoutParams(params);

        int dp_10 = SizeUtils.dp2px(10);
        LinearLayoutHelper appraiseHelper = new LinearLayoutHelper(dp_10);
        appraiseHelper.setBgColor(ContextCompat.getColor(mContext, R.color.colorTransparent));
        appraiseHelper.setMargin(0, dp_10, 0, dp_10);
        appraiseAdapter = new CommVLayoutAdapter<PostCommentInfo>(mContext, new ArrayList<>(),
                R.layout.item_forum_dynamic_appraise_child, appraiseHelper) {
            @Override
            public void convert(ViewHolder holder, int position, PostCommentInfo item) {
                GlideUtil.loadImageViewCrop(mContext, item.getAuthorPhoto(),
                        holder.getView(R.id.iv_item_avatar), R.drawable.shape_circle, R.drawable.shape_circle);
                holder.setText(R.id.tv_item_name, item.getAuthorName());
                holder.setText(R.id.tv_item_car_brand, item.getAuthorRemark());
                holder.setText(R.id.tv_item_time, AppCommonUtil.friendlyTime(item.getCreateTime()));
                holder.setText(R.id.tv_item_reply, item.getReplyCount() > 0 ? item.getReplyCount() + "回复" : "回复");
                holder.setText(R.id.tv_item_appraise_content, item.getContent() + "");
                TextView rtv_item_zan_count = holder.getView(R.id.rtv_item_zan_count);
                rtv_item_zan_count.setText(item.getLikeCount() + "");
                Drawable drawable1 = getResources().getDrawable(item.isLike() ? R.mipmap.ic_follow_36_s : R.mipmap.ic_follow_48);
                drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight());
                rtv_item_zan_count.setCompoundDrawables(drawable1, null, null, null);
                rtv_item_zan_count.setOnClickListener(new NoDoubleClickListener() {
                    @Override
                    public void onNoDoubleClick(View view) {
                        mvpPresenter.doDianZan(item.getId(), position);
                    }
                });
                holder.getView(R.id.tv_item_reply).setOnClickListener(new NoDoubleClickListener() {
                    @Override
                    public void onNoDoubleClick(View view) {
                        retInputContent.setHint("回复 " + item.getAuthorName());
                        retInputContent.setText("");
                        retInputContent.setTag(item);
                        KeyboardUtils.showSoftInput(retInputContent);
                    }
                });
                RadiusTextView rtv_reply_info = holder.getView(R.id.rtv_reply_info);
                if(!StringUtils.isTrimEmpty(item.getReplyContent())){
                    rtv_reply_info.setVisibility(View.VISIBLE);
                    rtv_reply_info.setText("回复//@" + item.getReplyName() + ":" + item.getReplyContent());
                }else{
                    rtv_reply_info.setVisibility(View.GONE);
                }
            }
        };
        /*appraiseAdapter.setItemClickListener(new CommVLayoutAdapter.OnItemClickListener<PostCommentInfo>() {
            @Override
            public void onItemClick(View view, int position, PostCommentInfo item) {
                retInputContent.setHint("发表评论");
                retInputContent.setText("");
                KeyboardUtils.showSoftInput(retInputContent);
            }
        });*/
        listAdapter.addAdapter(appraiseAdapter);
        mvpPresenter.getCommentInfo();
    }

    private void setCommentInfo(){
        GlideUtil.loadImageViewCrop(mContext, commentInfo.getAuthorPhoto(),
                ivPersonAvatar, R.drawable.shape_circle, R.drawable.shape_circle);
        tvPersonName.setText(commentInfo.getAuthorName());
        tvPersonCarBrand.setText(commentInfo.getAuthorRemark());
        tvCommentContent.setText(commentInfo.getContent());
        tvCommentTime.setText(AppCommonUtil.friendlyTime(commentInfo.getCreateTime()));
        rtvPersonZanCount.setText(commentInfo.getLikeCount() + "");
        Drawable drawable1 = getResources().getDrawable(commentInfo.isLike() ? R.mipmap.ic_follow_36_s : R.mipmap.ic_follow_48);
        drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight());
        rtvPersonZanCount.setCompoundDrawables(drawable1, null, null, null);
    }

    @Subscribe
    public void onSoftKeyboardShowOrHideEvent(SoftKeyboardShowOrHideEvent event) {
        if(event.getState() == 1){
            llBottomInfoPanel.setVisibility(View.GONE);
            llBottomInputPanel.setVisibility(View.VISIBLE);
        }else{
            llBottomInfoPanel.setVisibility(View.VISIBLE);
            llBottomInputPanel.setVisibility(View.GONE);
            retInputContent.setTag(null);
        }
    }

    @Override
    protected ForumAppraiseDetailsPresenter createPresenter() {
        return new ForumAppraiseDetailsPresenter(this);
    }

    @Override
    public void onGetCommentInfoSuccess(BaseModel<PostCommentInfo> successResult) {
        commentInfo = successResult.getData();
        setCommentInfo();
        loadingLayout.setStatus(LoadingLayout.Success);
        mvpPresenter.getCommentList(1);
    }

    @Override
    public void onGetCommentInfoFailure(BaseModel<Object> failureResult) {
        if (failureResult.getResultCode() == Constants.PAGE_DATA_EMPTY) {
            loadingLayout.setStatus(LoadingLayout.Empty);
            loadingLayout.setEmptyText(failureResult.getResultInfo());
        } else {
            loadingLayout.setStatus(LoadingLayout.Error);
            loadingLayout.setErrorText(failureResult.getResultInfo());
        }
    }

    @Override
    public void onGetCommentListSuccess(BaseModel<BasePage<PostCommentInfo>> successResult) {
        page = successResult.getData();
        if (refreshLayout.getState() == RefreshState.Refreshing) {
            refreshLayout.finishRefresh();
            appraiseAdapter.getData().clear();
            appraiseAdapter.getData().addAll(page.getItems());
            appraiseAdapter.notifyDataSetChanged();
        } else if (refreshLayout.getState() == RefreshState.Loading) {
            appraiseAdapter.getData().addAll(page.getItems());
            appraiseAdapter.notifyDataSetChanged();
            if (page.getTotalRecordCount() <= appraiseAdapter.getData().size()) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                refreshLayout.finishLoadMore(true);
            }
        } else {
            refreshLayout.finishRefresh();
            appraiseAdapter.getData().clear();
            appraiseAdapter.getData().addAll(page.getItems());
            appraiseAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onGetCommentListFailure(BaseModel<Object> failureResult) {
        if (Constants.PAGE_DATA_EMPTY == failureResult.getResultCode()) {
            if (refreshLayout.getState() == RefreshState.Refreshing) {
                refreshLayout.finishRefresh(true);
                if (appraiseAdapter.getData().size() > 0) {
                    appraiseAdapter.getData().clear();
                    appraiseAdapter.notifyDataSetChanged();
                }
            } else if (refreshLayout.getState() == RefreshState.Loading) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            }
        } else {
            if (refreshLayout.getState() == RefreshState.Refreshing) {
                refreshLayout.finishRefresh(false);
            }
            if (refreshLayout.getState() == RefreshState.Loading) {
                refreshLayout.finishLoadMore(false);
            }
        }
    }

    @Override
    public void onAddCommentSuccess(BaseModel<PostCommentInfo> successResult) {
        appraiseAdapter.getData().add(successResult.getData());
        appraiseAdapter.notifyDataSetChanged();
        recycler.scrollToPosition(appraiseAdapter.getData().size() - 1);
        EventBus.getDefault().post(new PostCommentChildAppraiseChangeEvent(getPostId(), getCommentId(), successResult.getData()));
    }

    @Override
    public void onAddCommentFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Override
    public void onDoDianZanSuccess(BaseModel<Integer> successResult) {
        if (successResult.getData() >= 0) {
            PostCommentInfo commentInfo = appraiseAdapter.getData().get(successResult.getData());
            if (commentInfo.isLike()) {
                commentInfo.setLikeCount(commentInfo.getLikeCount() - 1);
            } else {
                commentInfo.setLikeCount(commentInfo.getLikeCount() + 1);
            }
            commentInfo.setLike(!commentInfo.isLike());
            appraiseAdapter.notifyItemChanged(successResult.getData());
        } else {
            if (commentInfo.isLike()) {
                commentInfo.setLikeCount(commentInfo.getLikeCount() - 1);
            } else {
                commentInfo.setLikeCount(commentInfo.getLikeCount() + 1);
            }
            commentInfo.setLike(!commentInfo.isLike());
            rtvPersonZanCount.setText(commentInfo.getLikeCount() + "");
            Drawable drawable1 = getResources().getDrawable(commentInfo.isLike() ? R.mipmap.ic_follow_36_s : R.mipmap.ic_follow_48);
            drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight());
            rtvPersonZanCount.setCompoundDrawables(drawable1, null, null, null);
            EventBus.getDefault().post(new PostCommentChildLikeChangeEvent(commentInfo.getId()));
        }
    }

    @Override
    public void onDoDianZanFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Override
    public String getPostId() {
        return postId;
    }

    @Override
    public String getCommentId() {
        return commentId;
    }

    @OnClick({R.id.iv_person_avatar, R.id.tv_person_name, R.id.tv_person_car_brand, R.id.rtv_person_zan_count, R.id.rtv_text_content})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_person_avatar:
            case R.id.tv_person_name:
            case R.id.tv_person_car_brand:
                break;
            case R.id.rtv_person_zan_count:
                mvpPresenter.doDianZan(getCommentId(), -1);
                break;
            case R.id.rtv_text_content:
                retInputContent.setHint("发表评论");
                retInputContent.setText("");
                retInputContent.setTag(null);
                KeyboardUtils.showSoftInput(retInputContent);
                break;
        }
    }
}
